/*
 * VaaniView.java
 */

package vaani;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import javax.speech.recognition.GrammarException;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import vaani.internal.ProcessInstance;
import vaani.internal.actionmanagers.ActionManager;
import vaani.shabd.Analyzer;
import vaani.swar.SpeechHandler;

/**
 * The application's main frame.
 */
public class VaaniView extends FrameView {

    private ActionManager actionManager;
    private DefaultListModel listModel;

    public VaaniView(SingleFrameApplication app) {
        super(app);
        listModel = new DefaultListModel();
        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = VaaniApp.getApplication().getMainFrame();
            aboutBox = new VaaniAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        VaaniApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        speckButton = new javax.swing.JButton();
        doButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        textCommandField = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        activityList = new JList(listModel);
        jPanel4 = new javax.swing.JPanel();
        performButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        clearMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        speechMenuItem = new javax.swing.JCheckBoxMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setMaximumSize(new java.awt.Dimension(489, 300));
        mainPanel.setMinimumSize(new java.awt.Dimension(489, 300));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(489, 300));
        mainPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 20, 20));

        jPanel1.setMaximumSize(new java.awt.Dimension(477, 33));
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setPreferredSize(new java.awt.Dimension(477, 33));

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(vaani.VaaniApp.class).getContext().getActionMap(VaaniView.class, this);
        speckButton.setAction(actionMap.get("speakButtonHandler")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(vaani.VaaniApp.class).getContext().getResourceMap(VaaniView.class);
        speckButton.setLabel(resourceMap.getString("speckButton.label")); // NOI18N
        speckButton.setName("speckButton"); // NOI18N

        doButton.setAction(actionMap.get("doButtonHandler")); // NOI18N
        doButton.setText(resourceMap.getString("doButton.text")); // NOI18N
        doButton.setName("doButton"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(speckButton, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 332, Short.MAX_VALUE)
                .addComponent(doButton)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(speckButton)
                    .addComponent(doButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        mainPanel.add(jPanel1);

        jPanel2.setMaximumSize(new java.awt.Dimension(477, 40));
        jPanel2.setName("jPanel2"); // NOI18N
        jPanel2.setPreferredSize(new java.awt.Dimension(477, 40));

        textCommandField.setText(resourceMap.getString("textCommandField.text")); // NOI18N
        textCommandField.setName("textCommandField"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(textCommandField, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(textCommandField, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
                .addContainerGap())
        );

        mainPanel.add(jPanel2);

        jPanel3.setMaximumSize(new java.awt.Dimension(477, 100));
        jPanel3.setName("jPanel3"); // NOI18N
        jPanel3.setPreferredSize(new java.awt.Dimension(477, 100));

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        activityList.setName("activityList"); // NOI18N
        jScrollPane2.setViewportView(activityList);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 453, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
                .addGap(24, 24, 24))
        );

        mainPanel.add(jPanel3);

        jPanel4.setMaximumSize(new java.awt.Dimension(477, 40));
        jPanel4.setName("jPanel4"); // NOI18N
        jPanel4.setPreferredSize(new java.awt.Dimension(477, 40));

        performButton.setAction(actionMap.get("performButtonHandler")); // NOI18N
        performButton.setText(resourceMap.getString("performButton.text")); // NOI18N
        performButton.setName("performButton"); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGap(190, 190, 190)
                .addComponent(performButton)
                .addContainerGap(197, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(performButton)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        mainPanel.add(jPanel4);

        menuBar.setMaximumSize(new java.awt.Dimension(489, 21));
        menuBar.setMinimumSize(new java.awt.Dimension(489, 21));
        menuBar.setName("menuBar"); // NOI18N
        menuBar.setPreferredSize(new java.awt.Dimension(489, 21));

        fileMenu.setAction(actionMap.get("clearMenuItemAction")); // NOI18N
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setMaximumSize(new java.awt.Dimension(37, 19));
        fileMenu.setMinimumSize(new java.awt.Dimension(37, 19));
        fileMenu.setName("fileMenu"); // NOI18N

        clearMenuItem.setAction(actionMap.get("clearMenuItemAction")); // NOI18N
        clearMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
        clearMenuItem.setText(resourceMap.getString("clearMenuItem.text")); // NOI18N
        clearMenuItem.setName("clearMenuItem"); // NOI18N
        fileMenu.add(clearMenuItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setAction(actionMap.get("speechMenuItemHandler")); // NOI18N
        editMenu.setText(resourceMap.getString("editMenu.text")); // NOI18N
        editMenu.setMaximumSize(new java.awt.Dimension(39, 30));
        editMenu.setMinimumSize(new java.awt.Dimension(39, 30));
        editMenu.setName("editMenu"); // NOI18N
        editMenu.setPreferredSize(new java.awt.Dimension(39, 30));
        editMenu.setRequestFocusEnabled(false);

        speechMenuItem.setAction(actionMap.get("speechMenuItemHandler")); // NOI18N
        speechMenuItem.setSelected(true);
        speechMenuItem.setText(resourceMap.getString("speechMenuItem.text")); // NOI18N
        speechMenuItem.setMaximumSize(new java.awt.Dimension(165, 19));
        speechMenuItem.setMinimumSize(new java.awt.Dimension(165, 19));
        speechMenuItem.setName("speechMenuItem"); // NOI18N
        editMenu.add(speechMenuItem);

        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        editMenu.add(jMenuItem1);

        menuBar.add(editMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setMaximumSize(new java.awt.Dimension(45, 19));
        helpMenu.setMinimumSize(new java.awt.Dimension(45, 19));
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setMaximumSize(new java.awt.Dimension(489, 25));
        statusPanel.setMinimumSize(new java.awt.Dimension(489, 25));
        statusPanel.setName("statusPanel"); // NOI18N
        statusPanel.setPreferredSize(new java.awt.Dimension(489, 25));

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 451, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void doButtonHandler() {
        clearList();
        String commandPhrase = textCommandField.getText();
        System.out.println(commandPhrase);
        Analyzer analyzer = new Analyzer();
        actionManager = analyzer.analyze(commandPhrase);
        List<ProcessInstance> instances = actionManager.getProcessInstance();
        if(instances != null) {
            clearList();
            for(ProcessInstance instance : instances) {
                listModel.addElement(instance.getDescription());
            }
            activityList.ensureIndexIsVisible(listModel.size() -1);
            activityList.setSelectedIndex(0);
            activityList.repaint();
        }
    }

    public void clearList() {
        listModel.removeAllElements();
        activityList.repaint();
    }

    /*private class actionButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            ActionJRadioButton button = (ActionJRadioButton) event.getSource();
            if(! actionManager.equals(null)) {
                actionManager.runProcess(button.getActionNumber());
            }
            else {
                System.out.println("Could not execute command, application manager is not ready");
            }
        }
    }*/

    @Action
    public void clearMenuItemAction() {
        actionManager = null;
        //System.out.println("called");
        clearList();
        textCommandField.setText(null);
        textCommandField.repaint();
    }

    @Action
    public void performButtonHandler() {
        int index = activityList.getSelectedIndex();
        actionManager.runProcess(index);
    }

    @Action
    public void speakButtonHandler() {
        clearList();
        if(! SpeechHandler.isAvailable()) {
            SpeechHandler.init();
        }
        String retrievedString = null;
        try {
            retrievedString = SpeechHandler.execute();
        } catch(GrammarException ex) {
            ex.printStackTrace();
        } catch(IOException ex) {
            ex.printStackTrace();
        }
        if(retrievedString != null) {
            textCommandField.setText(retrievedString);
        } else {
            System.out.println("Could not recover the spoken phrase");
        }
    }

    @Action
    public void speechMenuItemHandler() {
        if(speechMenuItem.isSelected()) {
            SpeechHandler.stop();
            //speechMenuItem.setText("Enable Speech");
            //speechMenuItem.repaint();
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList activityList;
    private javax.swing.JMenuItem clearMenuItem;
    private javax.swing.JButton doButton;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton performButton;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JButton speckButton;
    private javax.swing.JCheckBoxMenuItem speechMenuItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTextField textCommandField;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}
